﻿CREATE PROCEDURE [dbo].[DepartmentUsersUpdate]
(
	@FirstName varchar(50),
	@SecondName varchar(50),
	@LastName varchar(50),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int

SET NOCOUNT ON

IF (@Original_Id Is Null) OR (@Original_MD Is Null) 
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @intRet = Id
FROM [CD].[DepartmentUsers] WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
	SET NOCOUNT OFF;
UPDATE [CD].[DepartmentUsers] SET [FirstName] = @FirstName, [SecondName] = @SecondName, [LastName] = @LastName, [Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id;
	
SELECT Id, DepartmentId, Login, FirstName, SecondName, LastName, Note, MD, MW 
FROM CD.DepartmentUsers WHERE (Id = @Original_Id)

RETURN 0